 /*Hdip Project 2013-14, Student Name:- Chris Pembroke,  Student Number:- x00115839*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;

//using CustomerBikeService.Models;

namespace Exercise1Project.Models
{
    public interface IBikeRepository  // bike  repository interface
    {
        IEnumerable<Bike> GetBikeByCustomerID(string id); // index or list all a customers bicycles (can give bike Detail as well) crud  D
        Bike AddCustomerBike(Bike bikeToAdd);   // create  (add a new bike to list) crud  C
        void RemoveCustomerBike(int id);       // delete (remove a bike from existing list) crud R
        Bike UpdateBikeDetail(Bike bikeToUpdate);     // Update action is EDIT  crud  U
        Bike GetBikeByBikeId(int id);              // get a particurlar bike from the list of bikes
        int SaveChanges();  // save created or updated changes to database table

    } // close of interface ibikerepository

    public class BikeRepository : IBikeRepository // bikerepository class implements bike repository interface
    {
        private BicycleRepairEntities _db = new BicycleRepairEntities();   // ties in with bike entities which in turn ties in with bike class which ties in with bike table

        public IEnumerable<Bike> GetBikeByCustomerID(string id)  // index view or list of all bikes in bike table
        {
                return _db.Bikes.ToList().Where(d => d.CustomerID == id); 
        }

        public Bike GetBikeByBikeId(int id)  // search bike table for a bikes used with update and delete
        {
            return _db.Bikes.FirstOrDefault(d => d.BikeID == id);
        }

        public int SaveChanges()  // persist changes in database table used for create, update, delete
        {
            return _db.SaveChanges();
        }

        public Bike AddCustomerBike(Bike bikeToAdd)  // create view
        {
            _db.Bikes.Add(bikeToAdd);
            _db.SaveChanges();
            return bikeToAdd;
        }

        
        public Bike UpdateBikeDetail(Bike bikeToUpdate)            // Edit action or update of crud
        {
            //Bike bikeToEdit = GetBikeByBikeId(bikeToUpdate.BikeID);                    // get original contact (this sits in the dbcontext)
            _db.Entry(bikeToUpdate).State = EntityState.Modified;
            _db.SaveChanges();                                                       // save changes to database
            return bikeToUpdate;
        }
        



        public void RemoveCustomerBike(int id)  // Delete action or remove of crud
        {
            Bike bikeToRemove = GetBikeByBikeId(id);
            _db.Bikes.Remove(bikeToRemove);
            _db.SaveChanges();
        }


    } // close of class bikerepository

} // close of namespace